package com.viaas.certification.image.action;

import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import org.bukkit.scheduler.BukkitRunnable;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

public class AIModeManager {
    private final Plugin plugin;
    private final Map<Player, Boolean> aiEnabled = new HashMap<>();
    private final Random random = new Random();

    public AIModeManager(Plugin plugin) {
        this.plugin = plugin;
    }

    // 开启 AI 接管模式
    public void enableAI(Player player) {
        if (aiEnabled.getOrDefault(player, false)) {
            player.sendMessage(ChatColor.RED + "AI 已经在控制你的角色！");
            return;
        }

        aiEnabled.put(player, true);
//        player.setGameMode(GameMode.SPECTATOR); // 让玩家进入观察者模式

        Bukkit.broadcastMessage(ChatColor.GREEN + player.getName() + " 已开启 AI 模式，AI 正在接管！");

        new BukkitRunnable() {
            @Override
            public void run() {
                if (!aiEnabled.getOrDefault(player, false)) {
                    cancel();
                    return;
                }

                // 随机选择 AI 行为
                int action = random.nextInt(4);
                if (action == 0) moveRandomly(player);
                if (action == 1) attackNearest(player);
                if (action == 2) jump(player);
                if (action == 3) interact(player);
            }
        }.runTaskTimer(plugin, 0, 40);
    }

    // 关闭 AI 接管模式
    public void disableAI(Player player) {
        if (!aiEnabled.getOrDefault(player, false)) {
            player.sendMessage(ChatColor.RED + "AI 模式未开启！");
            return;
        }

        aiEnabled.put(player, false);
        player.setGameMode(GameMode.SURVIVAL);
        player.sendMessage(ChatColor.YELLOW + "AI 模式已关闭，你可以正常操作角色了！");
        Bukkit.broadcastMessage(ChatColor.RED + player.getName() + " 关闭了 AI 模式，恢复手动控制！");
    }

    // 让 AI 控制玩家移动
    private void moveRandomly(Player player) {
        Location loc = player.getLocation();
        Location newLoc = loc.clone().add(random.nextInt(6) - 3, 0, random.nextInt(6) - 3);
        player.teleport(newLoc);
        Bukkit.broadcastMessage(ChatColor.GRAY + player.getName() + " 正在自动移动...");
    }

    // 让 AI 控制玩家攻击
    private void attackNearest(Player player) {
        player.swingMainHand(); // 让玩家摆动手臂
        Bukkit.broadcastMessage(ChatColor.RED + player.getName() + " 正在自动攻击！");
    }

    // 让 AI 控制玩家跳跃
    private void jump(Player player) {
        player.setVelocity(player.getVelocity().setY(0.5));
        Bukkit.broadcastMessage(ChatColor.YELLOW + player.getName() + " 正在自动跳跃！");
    }

    // 让 AI 控制玩家执行交互
    private void interact(Player player) {
        Bukkit.broadcastMessage(ChatColor.LIGHT_PURPLE + player.getName() + " 试图与环境交互！");
    }
}
